//! 数据网关性能基准测试
//! 
//! 测试核心模块的性能指标，包括：
//! - 微内核系统性能
//! - 脚本解析器性能
//! - 数据层转换性能
//! - 查询处理性能

use criterion::{black_box, criterion_group, criterion_main, Criterion, BenchmarkId};
use std::time::Duration;
use tokio::runtime::Runtime;

// 导入核心模块
use data_gateway_kernel::{DataGatewayKernel, Query, QueryType};
use data_gateway_parser::{parse_script, execute_script, ScriptContext};
use data_gateway_data_layer::ArrowBridge;
use serde_json::json;

/// 微内核系统性能测试
fn benchmark_kernel_performance(c: &mut Criterion) {
    let rt = Runtime::new().unwrap();
    
    c.bench_function("kernel_startup", |b| {
        b.to_async(&rt).iter(|| async {
            let kernel = black_box(DataGatewayKernel::new().await.unwrap());
            drop(kernel);
        });
    });
    
    // 测试查询创建性能
    let mut group = c.benchmark_group("query_creation");
    for query_type in [QueryType::Sql, QueryType::Script, QueryType::GraphQL].iter() {
        group.bench_with_input(
            BenchmarkId::new("create_query", format!("{:?}", query_type)),
            query_type,
            |b, &query_type| {
                b.iter(|| {
                    let query = black_box(Query::new(
                        "SELECT * FROM test".to_string(),
                        query_type.clone(),
                    ));
                    query
                });
            },
        );
    }
    group.finish();
}

/// 脚本解析器性能测试
fn benchmark_parser_performance(c: &mut Criterion) {
    let rt = Runtime::new().unwrap();
    
    // 测试不同复杂度的脚本解析性能
    let scripts = vec![
        ("simple", "var x = 10; var y = 20; var result = x + y;"),
        ("medium", r#"
            var sum = 0;
            for (var i = 0; i < 100; i = i + 1) {
                sum = sum + i;
            }
            print("Sum: " + sum);
        "#),
        ("complex", r#"
            function fibonacci(n) {
                if (n <= 1) {
                    return n;
                } else {
                    return fibonacci(n - 1) + fibonacci(n - 2);
                }
            }
            
            var result = fibonacci(10);
            print("Fibonacci(10): " + result);
        "#),
    ];
    
    let mut group = c.benchmark_group("script_parsing");
    for (name, script) in scripts.iter() {
        group.bench_with_input(
            BenchmarkId::new("parse_script", name),
            script,
            |b, &script| {
                b.iter(|| {
                    let program = black_box(parse_script(script).unwrap());
                    program
                });
            },
        );
    }
    group.finish();
    
    let mut group = c.benchmark_group("script_execution");
    for (name, script) in scripts.iter() {
        group.bench_with_input(
            BenchmarkId::new("execute_script", name),
            script,
            |b, &script| {
                b.to_async(&rt).iter(|| async {
                    let context = ScriptContext::new();
                    let result = black_box(execute_script(script, context).await.unwrap());
                    result
                });
            },
        );
    }
    group.finish();
}

/// 数据层性能测试
fn benchmark_data_layer_performance(c: &mut Criterion) {
    let mut bridge = ArrowBridge::new();
    
    // 测试不同大小的数据转换性能
    let data_sizes = vec![10, 100, 1000, 10000];
    
    let mut group = c.benchmark_group("json_to_arrow_conversion");
    for &size in data_sizes.iter() {
        let json_data: Vec<_> = (0..size)
            .map(|i| json!({
                "id": i,
                "name": format!("user_{}", i),
                "age": 20 + (i % 50),
                "score": 80.0 + (i as f64 % 20.0),
                "active": i % 2 == 0
            }))
            .collect();
        
        group.bench_with_input(
            BenchmarkId::new("convert", size),
            &json_data,
            |b, data| {
                b.iter(|| {
                    let mut bridge = ArrowBridge::new();
                    let record_batch = black_box(bridge.json_to_arrow(data).unwrap());
                    record_batch
                });
            },
        );
    }
    group.finish();
    
    // 测试Arrow到JSON转换性能
    let mut group = c.benchmark_group("arrow_to_json_conversion");
    for &size in data_sizes.iter() {
        let json_data: Vec<_> = (0..size)
            .map(|i| json!({
                "id": i,
                "name": format!("user_{}", i),
                "age": 20 + (i % 50),
                "score": 80.0 + (i as f64 % 20.0),
                "active": i % 2 == 0
            }))
            .collect();
        
        let record_batch = bridge.json_to_arrow(&json_data).unwrap();
        
        group.bench_with_input(
            BenchmarkId::new("convert", size),
            &record_batch,
            |b, batch| {
                b.iter(|| {
                    let mut bridge = ArrowBridge::new();
                    let json_data = black_box(bridge.arrow_to_json(batch).unwrap());
                    json_data
                });
            },
        );
    }
    group.finish();
}

/// 内存使用性能测试
fn benchmark_memory_performance(c: &mut Criterion) {
    let rt = Runtime::new().unwrap();
    
    c.bench_function("memory_allocation", |b| {
        b.to_async(&rt).iter(|| async {
            // 创建大量对象测试内存分配性能
            let mut objects = Vec::new();
            for i in 0..1000 {
                let query = Query::sql(format!("SELECT * FROM table_{}", i));
                objects.push(black_box(query));
            }
            objects
        });
    });
}

/// 并发性能测试
fn benchmark_concurrency_performance(c: &mut Criterion) {
    let rt = Runtime::new().unwrap();
    
    c.bench_function("concurrent_script_execution", |b| {
        b.to_async(&rt).iter(|| async {
            let script = "var x = 10; var y = 20; var result = x + y;";
            
            // 并发执行多个脚本
            let tasks: Vec<_> = (0..10)
                .map(|_| {
                    let script = script.to_string();
                    tokio::spawn(async move {
                        let context = ScriptContext::new();
                        execute_script(&script, context).await.unwrap()
                    })
                })
                .collect();
            
            // 等待所有任务完成
            for task in tasks {
                black_box(task.await.unwrap());
            }
        });
    });
}

criterion_group!(
    benches,
    benchmark_kernel_performance,
    benchmark_parser_performance,
    benchmark_data_layer_performance,
    benchmark_memory_performance,
    benchmark_concurrency_performance
);

criterion_main!(benches);
